import axios from "axios";
// 引入进度条
import nprogress from 'nprogress'
//  引入进度条的样式
import 'nprogress/nprogress.css'
class Request {
  // 自定义变量
  instance;
  constructor(config) {
    // 创建axios 实例，变量接收
    this.instance = axios.create(config);
    // 添加请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        nprogress.start()
        config.headers.Authorization = "Bearer" + ' ' + localStorage.getItem("token")
        return config;
      },
      (error) => {
        return error;
      }
    );
    // 添加相应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        nprogress.done()
        // console.log(res.data,213)
        return res.data;
      },
      (error) => {
        // console.log(error, "相应错误")
        return error;
      }
    );
  }
  // 2
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance.request(config).then((res) => {
        return resolve(res);
      }).catch((error) => {
        return reject(error);
      });
    });
  }


  // 1
  get(config) {
    return this.request({
      ...config,
      method: "GET",
    });
  }
  post(config) {
    const formData = new FormData()
    for (const key in config.params) {
      formData.append(key, config.params[key])
    }
    return this.request({
      data: formData,
      url: config.url,
      method: "POST",
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
  postjson(config) {
    return this.request({
      ...config,
      method: "POST",
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }
}

export default Request;
